package com.deyuanyun.pic.web.interceptor;

import com.deyuanyun.pic.common.dto.Result;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 为获取当前操作的request和response提供支持
 * spring use  ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
 * SqlUtil.clearLocalPage();
 */
public class RequestAndResponseInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = Logger.getLogger(RequestAndResponseInterceptor.class);
    //大url地址和菜单id的对应关系
    private static Map<String,String> urlIdMap=new HashMap<>();
    /*static {
        urlIdMap.put("cleanTask","M0000000000000004000000000000000");
        urlIdMap.put("pig","M0000000000000004000000000000000");
        urlIdMap.put("basedata","M0000000000000001000000000000000");
        urlIdMap.put("risk","M0000000000000006000000000000000");
        urlIdMap.put("insp","M0000000000000002000000000000000");
        urlIdMap.put("hca","M0000000000000005000000000000000");
        urlIdMap.put("settings","M0000000000000003000000000000000");
    }*/

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
        //统一增加一些页面变量
        request.setAttribute("nowDateTime_",new Date());
        request.setAttribute("jsfileVersion_","?vv=1");
        RequestResponseContext.setRequest(request);
        RequestResponseContext.setResponse(response);

        String method=request.getMethod();
        /*if ("GET".equalsIgnoreCase(method)) {
            String requestUrl = request.getRequestURI();
            String context = request.getContextPath();
            requestUrl=StringUtils.removeStart(requestUrl,context);
            String rhost=request.getRemoteHost();
            String menuMark=urlIdMap.get(StringUtils.substringBetween(requestUrl,"/","/"));
            if (StringUtils.isNotBlank(menuMark)){
                request.setAttribute("menuMark",menuMark);
                UserSessionVO sessionVO= SessionCacheSupport2.getSessionVO();
                if (sessionVO!=null){
                    Menu m= sessionVO.getMenuById(menuMark);
                    if (m!=null){
                        request.setAttribute("menuImg",m.getImgUrl());
                    }
                    Menu subM=sessionVO.getMenuByUrl(menuMark,requestUrl);
                    if (subM!=null){
                        request.setAttribute("menuActive__",subM.getParentId());
                        request.setAttribute("menuActive_subMenu__",subM.getId());
                    }

                }
            }
        }*/


         String mod= ServletRequestUtils.getStringParameter(request,"AjaxMode","");
        if (StringUtils.isNotBlank(mod)){
            int pageNum = ServletRequestUtils.getIntParameter(request,"jsonBean.pageNum",0);
            int pageCount = ServletRequestUtils.getIntParameter(request,"jsonBean.pageCount",0);
            if (pageNum==0 && pageCount==0){
                //todo
            }else {
                //PageHelper.startPage(pageNum,pageCount);
                Result r=new Result();
                r.setPageNum(pageNum);
                r.setPageSize(pageCount);
                RequestResponseContext.setTempPageInfo(r);
            }
        }


        //防重复提交验证
        /*SessionVO sessionVO = SessionCacheSupport2.getSessionVO();
        if(sessionVO!=null){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            AvoidDuplicateSubmission annotation = method.getAnnotation(AvoidDuplicateSubmission.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.needSaveToken();
                if (needSaveSession) {
                    request.getSession(false).setAttribute("_token", sessionVO.getLoginId()+UUIDUtil.getUUID());
                }

                boolean needRemoveSession = annotation.needRemoveToken();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        logger.warn("please don't repeat submit,[user:" + sessionVO.getLoginId() + ",url:"
                                + request.getServletPath() + "]");
                        AjaxSupport.sendFailText("提交失败","请不要重复提交");
                        return false;
                    }
                    request.getSession(false).removeAttribute("_token");
                }
            }
        }*/
        return true;


    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute("_token");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("_token");
        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }

}
